package com.roy.comet.parse;

import com.alibaba.druid.sql.parser.Lexer;
import com.alibaba.druid.sql.parser.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by mc on 18/4/13.
 */
@Service
public class CometSqlParserImpl implements CometSqlParser {

    private static final Logger log = LoggerFactory.getLogger(CometSqlParserImpl.class);

    private static final int CACHE_SIZE = 1000;

    @SuppressWarnings("unchecked")
    private Map<String, CometSqlBean> cache = new ConcurrentHashMap<>(CACHE_SIZE);

    @Override
    public CometSqlBean parseCometSql(String sql) {
        CometSqlBean cometSqlBean = cache.get(sql);

        if (cometSqlBean != null) {
            return cometSqlBean;
        }
        cometSqlBean = new CometSqlBean();

        String dbName = null;
        String tableName = null;
        CometSqlBean.SqlType sqlType = null;

        Lexer lexer = new Lexer(sql);
        lexer.nextToken();
        Token tok = lexer.token();
        if(tok.name.equals("SELECT")){
            cometSqlBean = new SelectSqlParseStrategy().getCometSqlBean(cometSqlBean,lexer,sql,dbName,tableName);
        }
        if(tok.name.equals("INSERT")){
            cometSqlBean = new InsertSqlParseStrategy().getCometSqlBean(cometSqlBean,lexer,sql,dbName,tableName);
        }
        if(tok.name.equals("UPDATE")){
            cometSqlBean = new UpdateSqlParseStrategy().getCometSqlBean(cometSqlBean,lexer,sql,dbName,tableName);
        }
        return cometSqlBean;
    }

    /*public static void main(String[] args) {
        CometSqlParser cometSqlParser = new CometSqlParserImpl();
        CometSqlBean cometSqlBean = cometSqlParser.parseCometSql("insert into user values(5,'liutao',12);");
        System.out.print(cometSqlBean.getSplitSql(1,1));
    }*/
}
